import { Component, OnInit } from '@angular/core';
import { EChartOption } from 'echarts';
import { NotificationService } from 'app/shared/service';
import { DataManagementService } from '../data-management.services';
import * as moment from 'moment';
import { BullySubjectService } from 'app/shared/service';
import { MESSAGE_CHANNEL } from 'app/app.constants';
import { Subscription } from 'rxjs';
import { PublicService } from 'app/public/public.service';
import { SELECT_OPTIONS } from 'app/app.constants';
import { differenceInCalendarDays } from 'date-fns';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-traffic-data-report',
    templateUrl: './traffic-data-report.component.html',
    styleUrls: ['./traffic-data-report.component.css']
})
export class TrafficDataReportComponent implements OnInit {
    a = null;
    b = null;
    c = null;
    d = null;
    detectorID = null;
    roadName = null;
    thisDay = null;
    nextDay = null;
    startTime = null;
    endTime = null;
    roadSelect = null;
    roadOptions = [];
    includeSelect = '';
    includeOptions = [];
    intervalSelect = null;
    sourcelSelect = true;
    isShowEacharts = false;
    intervalOptions = [];
    dateRange = null;
    hisDateRange = null;
    renderHeader = []; // 表头数据的数组
    listOfData = []; // 列表数据的数组
    isTableShow = false;
    // 分页数据的对象
    pagination = {
        totalEle: 0,
        currentPage: 1,
        currentSize: 10,
        pageSize: 10
    };
    // 报表数据
    timeRange = [];
    volume = [];
    occupancy = [];
    speed = [];
    option1: EChartOption;
    option2: EChartOption;
    option3: EChartOption;
    echartsIntance1: any;
    echartsIntance2: any;
    echartsIntance3: any;
    todayTime: string;
    true = null;
    flag = false;
    road = null;
    subscription: Subscription = null;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    queryStartTime = null;
    queryEndTime = null;
    startTimeRange = null;
    endTimeRange = null;

    constructor(
        private DMService: DataManagementService,
        private message: NotificationService,
        private bully: BullySubjectService,
        private publicService: PublicService,
        private translate: TranslateService
    ) {}

    ngOnInit() {
        // this._setGisPosition();
        // this.getRoad();
        this.getData();
        this.getOption();
        this.renderHeader = [
            {
                name: 'TimeRange',
                key: null,
                value: 'timeRange'
            },
            {
                name: 'Volume(num.vehicles)',
                key: null,
                value: 'volume(num.vehicles)'
            },
            {
                name: 'AvgOccupancy',
                key: null,
                value: 'Avg.Occupancy(%)'
            },
            {
                name: 'AvgSpeed',
                key: null,
                value: 'Avg.Speed(km/h)'
            }
        ];
        this.includeOptions = [
            { name: 'Weekday', id: '1%7C2%7C3%7C4%7C5' },
            { name: 'Weekend', id: '6%7C7' },
            { name: 'All', id: '1%7C2%7C3%7C4%7C5%7C6%7C7' }
        ];
        this.intervalOptions = [
            { name: '5min', id: 1 },
            { name: '10min', id: 2 },
            { name: '15min', id: 3 },
            {
                name: '60min',
                id: 4
            }
        ];
        this.getButtonAccess();
    }

    getButtonAccess() {
        this.accessButton = this.publicService.getButtonAccess('27', this.accessButton);
    }

    onChartInit1(ec: any) {
        this.echartsIntance1 = ec;
    }

    onChartInit2(ec: any) {
        this.echartsIntance2 = ec;
    }

    onChartInit3(ec: any) {
        this.echartsIntance3 = ec;
    }

    // 获取报表
    getOption() {
        const tempData = ['Km/h / Speed(HH:mm/Time)', '%/Occupancy (HH:mm/Time)', 'Vehicles count/Volume (HH:mm/Time)'];
        const translateData = [];
        tempData.forEach(item => {
            this.translate.get('DataManagement.TrafficDataReport.' + item).subscribe((res: string) => {
                translateData.push(res);
            });
        });
        setTimeout(() => {
            this.option1 = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: translateData,
                    textStyle: {
                        color: '#ffffff' //图例颜色
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: this.timeRange,
                        splitLine: {
                            show: true
                        },
                        axisLabel: {
                            show: true,
                            textStyle: {
                                //x轴座标文字颜色
                                color: '#fff'
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                type: 'solid',
                                color: '#fff', //左边线的颜色
                                width: '1' //坐标线的宽度
                            }
                        }
                    }
                ],
                yAxis: {
                    type: 'value',
                    splitLine: {
                        show: true
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    }
                },
                series: [
                    {
                        name: translateData[0],
                        type: 'line',
                        data: this.speed
                    },
                    {
                        name: translateData[1],
                        type: 'line',
                        data: this.occupancy
                    },
                    {
                        name: translateData[2],
                        type: 'line',
                        data: this.volume
                    }
                ],
                dataZoom: [
                    {
                        type: 'slider',
                        show: false,
                        // start: 0,
                        // end: 50,
                        handleSize: 8
                    },
                    {
                        type: 'inside'
                        // start: 0,
                        // end: 50
                    }
                ]
            };
            this.option2 = {
                tooltip: {
                    trigger: 'axis'
                },
                // legend: {
                //     data: ['1:600', '2:180'],
                //     x: 'right'
                // },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: this.timeRange
                    }
                ],
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '1:600',
                        type: 'line',
                        data: this.occupancy
                    }
                ],
                dataZoom: [
                    {
                        type: 'slider',
                        show: true,
                        // start: 0,
                        // end: 50,
                        handleSize: 8
                    },
                    {
                        type: 'inside'
                        // start: 0,
                        // end: 50
                    }
                ]
            };
            this.option3 = {
                tooltip: {
                    trigger: 'axis'
                },
                // legend: {
                //     data: ['1:600', '2:180'],
                //     x: 'right'
                // },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: this.timeRange
                    }
                ],
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '1:600',
                        type: 'line',
                        data: this.speed
                    }
                ],
                dataZoom: [
                    {
                        type: 'slider',
                        show: true,
                        // start: 0,
                        // end: 50,
                        handleSize: 8
                    },
                    {
                        type: 'inside'
                        // start: 0,
                        // end: 50
                    }
                ]
            };
        });
    }

    getNowTime() {
        const day1 = new Date();
        const hour = day1.getHours(); // 得到小时
        const minu = day1.getMinutes(); // 得到分钟
        const second = day1.getSeconds();
        this.todayTime = `${hour}:${minu}:${second}`;
        this.thisDay = day1.getFullYear() + '-' + (day1.getMonth() + 1) + '-' + day1.getDate();
        const todayStart = this.thisDay + ` 00:00:00`;
        const todayEnd = this.thisDay + ` ${this.todayTime}`;
        this.dateRange = [todayStart, todayEnd];
        return day1;
    }

    // 获取数据
    getData() {
        // setInterval(() => {
        // 搜索实时数据禁用筛选框
        // if (this.sourcelSelect === 'current') {
        //     this.flag = true;
        // } else {
        //     this.flag = false;
        // }
        // 获取当天日期
        const day1 = this.getNowTime();
        // 获取明天日期
        this.nextDay = this.thisDay;
        const start = new Date(new Date(new Date().toLocaleDateString()).getTime()); // 获取当日的00:00
        // 赋值到筛选框
        this.startTime = start;
        this.endTime = new Date();
        this.a = this.startTime.toString();
        this.b = this.a.slice(16, 21);
        this.c = this.endTime.toString();
        this.d = this.c.slice(16, 21);
        this.includeSelect = '1%7C2%7C3%7C4%7C5%7C6%7C7';
        this.intervalSelect = '60min';
        // this.queryStartTime = this.thisDay;
        // this.queryEndTime = this.thisDay;
        // (this.startTimeRange = '00:00:00'), (this.endTimeRange = this.todayTime);
        const response = this.publicService.getSelectOptionsList(SELECT_OPTIONS.AID_EQUIP);
        const res = response.data;
        if (res) {
            this.roadOptions = [...res];
            if (localStorage.getItem('itmp_lang') === 'vi') {
                this.roadOptions.forEach(site => {
                    site.displayName = site.vietName;
                });
            } else {
                this.roadOptions.forEach(site => {
                    site.displayName = site.name;
                });
            }
            this.roadSelect = res[0].name;
            const road = this.roadSelect.split('<')[0];
            this.detectorID = this.roadSelect.split('<')[0];
            this.roadName = this.roadSelect.split('<')[1].slice(0, -1);
            this.road = this.roadSelect;
            const queryData = `startDateRange=${this.thisDay},endDateRange=${this.thisDay},startTimeRange=00:00:00,endTimeRange=${
                this.todayTime
            },interval=60min,deviceId=${road}`;
            this.DMService.getTraDataRep(queryData).subscribe(rest => {
                if (rest.messagecode === '000000') {
                    const timeRange = `00:00:00~${this.todayTime}`;
                    const timeInterval = this.intervalSelect.split('m')[0];
                    const resultData = this.DMService.generateAllData(timeInterval, rest.data, timeRange);
                    for (const item of resultData) {
                        this.timeRange.push(item.interval_zone);
                        this.volume.push(item.total_volume);
                        this.occupancy.push(item.avg_occ);
                        this.speed.push(item.avg_speed);
                    }
                    // 没有数据警告
                    if (resultData.length === 0) {
                        this.isShowEacharts = false;
                        this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
                    } else {
                        this.isShowEacharts = true;
                    }
                    this.getOption();
                }
            });
            this.getTableData(queryData);
        }
        this.changeLang();
        // }, this.intervalSelect);
    }

    changeLang() {
        this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.LANGUAGE_CHANNEL).subscribe(res => {
            if (res.data === 'vi') {
                this.roadOptions.forEach(site => {
                    site.displayName = site.vietName;
                });
                this.roadSelect = this.roadOptions[0];
            } else {
                this.roadOptions.forEach(site => {
                    site.displayName = site.name;
                });
                this.roadSelect = this.roadOptions[0];
            }
        });
    }

    // 获取road下拉框数据
    getTableData(queryData: string) {
        // 默认请求当前日期00:00到此刻的数据，间隔60min
        // 获取表格数据
        const pageNum = this.pagination.currentPage;
        const pageSize = this.pagination.pageSize;
        this.DMService.getTraDataRepTable(queryData, pageNum, pageSize).subscribe(rest => {
            if (rest.messagecode === '000000') {
                this.timeRange = [];
                this.volume = [];
                this.occupancy = [];
                this.speed = [];
                this.listOfData = rest.data.content;
                if (this.listOfData.length === 0) {
                    this.isTableShow = false;
                } else {
                    this.isTableShow = true;
                }
                this.pagination.currentPage = rest.data.pageNum;
                this.pagination.currentSize = rest.data.numberOfElements;
                this.pagination.totalEle = rest.data.totolElements;
            }
        });
    }

    getRoad() {
        this.DMService.getAllEnumInfo().subscribe(res => {
            if (res.code === '000000') {
                const data = [];
                res.data.forEach(ele => {
                    if (ele.category === 'AidEquip') {
                        data.push(ele);
                    }
                });
                this.roadOptions = data;
                this.roadSelect = data[0].name;
                // this.detectorID = this.roadSelect.slice(0, 1);
                // this.roadName = this.roadSelect.slice(1);
                this.detectorID = this.roadSelect.split('<')[0];
                this.roadName = this.roadSelect.split('<')[1].slice(0, -1);
                this.road = this.roadSelect;
            }
        });
    }

    // 搜索框
    search() {
        // tslint:disable-next-line:max-line-length
        // 点击搜索时更改页面表格上面的detector和road的显示

        if (!this.detectorID || !this.roadSelect) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.select_notify' });
        }
        this.detectorID = this.roadSelect.split('<')[0];
        this.roadName = this.roadSelect.split('<')[1].slice(0, -1);
        const { queryStartTime, queryEndTime, startTimeRange, endTimeRange } = this.getTimeFormat();
        if (
            queryStartTime === null ||
            queryEndTime === null ||
            startTimeRange === null ||
            endTimeRange === null ||
            this.intervalSelect === null
        ) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.select_notify' });
        } else {
            // tslint:disable-next-line: max-line-length
            // this.getNowTime();
            let a = '';
            let b = '';
            if (this.sourcelSelect) {
                // this.getNowTime();
                a = `startDateRange=${queryStartTime},endDateRange=${queryEndTime}`;
                b = `startTimeRange=00:00:00,endTimeRange=${endTimeRange},interval=${this.intervalSelect},deviceId=${this.detectorID}`;
            } else {
                a = `startDateRange=${queryStartTime},endDateRange=${queryEndTime}`;
                b = `startTimeRange=${startTimeRange},endTimeRange=${endTimeRange},interval=${this.intervalSelect},deviceId=${
                    this.detectorID
                }`;
            }
            // const a = this.sourcelSelect
            //     ? `startDateRange=${this.thisDay},endDateRange=${this.nextDay}`
            //     : `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime}`;
            // // tslint:disable-next-line: max-line-length
            // const b = this.sourcelSelect
            //     ? `startTimeRange=00:00:00,endTimeRange=${this.todayTime},interval=${this.intervalSelect},deviceId=${this.detectorID}`
            //     : `startTimeRange=${this.startTimeRange},endTimeRange=${this.endTimeRange},interval=${this.intervalSelect},deviceId=${
            //     this.detectorID
            //     }`;
            const queryData = `${a},${b}`;
            // this.thisDay = this.queryStartTime;
            // this.nextDay = this.queryEndTime;
            // 获取报表数据
            this.DMService.getTraDataRep(queryData).subscribe(res => {
                if (res.messagecode === '000000') {
                    const timeRange = this.sourcelSelect ? `00:00:00~${this.todayTime}` : `${startTimeRange}~${endTimeRange}`;
                    const timeInterval = this.intervalSelect.split('m')[0];
                    const resultData = this.DMService.generateAllData(timeInterval, res.data, timeRange);
                    this.timeRange = [];
                    this.volume = [];
                    this.occupancy = [];
                    this.speed = [];
                    for (const item of resultData) {
                        this.timeRange.push(item.interval_zone);
                        this.volume.push(item.total_volume);
                        this.occupancy.push(item.avg_occ);
                        this.speed.push(item.avg_speed);
                    }
                    if (resultData.length === 0) {
                        this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
                        this.isShowEacharts = false;
                    } else {
                        this.isShowEacharts = true;
                    }
                    this.getOption();
                }
            });
            // 获取分页数据
            // tslint:disable-next-line: max-line-length
            const c = this.sourcelSelect
                ? `startDateRange=${queryStartTime},endDateRange=${queryEndTime}`
                : `startDateRange=${queryStartTime},endDateRange=${queryEndTime},weekday=${this.includeSelect}`;
            const d = this.sourcelSelect
                ? `startTimeRange=00:00:00,endTimeRange=${endTimeRange},interval=${this.intervalSelect},deviceId=${this.detectorID}`
                : `startTimeRange=${startTimeRange},endTimeRange=${endTimeRange},interval=${this.intervalSelect},deviceId=${
                      this.detectorID
                  }`;
            const pageNum = this.pagination.currentPage;
            const pageSize = this.pagination.pageSize;
            const searchData = `${c},${d}`;
            this.DMService.getTraDataRepTable(searchData, pageNum, pageSize).subscribe(res => {
                if (res.messagecode === '000000') {
                    this.listOfData = [];
                    this.listOfData = res.data.content || [];
                    if (this.listOfData.length === 0) {
                        this.isTableShow = false;
                    } else {
                        this.isTableShow = true;
                    }
                    this.pagination.currentPage = res.data.pageNum;
                    this.pagination.currentSize = res.data.numberOfElements;
                    this.pagination.totalEle = res.data.totolElements;
                }
            });
        }
    }

    switchChange(changeFlag: boolean) {
        if (this.sourcelSelect) {
            const day = new Date();
            this.thisDay = day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate();
            const hour = day.getHours(); // 得到小时
            const minu = day.getMinutes(); // 得到分钟
            const second = day.getSeconds();
            this.todayTime = `${hour}:${minu}:${second}`;
            const todayStart = this.thisDay + ` 00:00:00`;
            const todayEnd = this.thisDay + ` ${this.todayTime}`;
            this.dateRange = [todayStart, todayEnd];
        } else if (this.hisDateRange) {
            this.dateRange = this.hisDateRange;
        }
    }

    // getGisPosition(key) {
    //     const bully = {
    //         type: MESSAGE_CHANNEL.CCM_CHANNEL,
    //         data: {
    //             data: key
    //         }
    //     };
    //     this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, bully);
    // }
    // private _setGisPosition() {
    //     this.subscription = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.MAP_CHANNEL).subscribe(res => {
    //         if (res.type === MESSAGE_CHANNEL.MAP_CHANNEL) {
    //             const features = res['data']['features'];
    //             const dataType = res['data']['dataType'];
    //             const value = {
    //                 [dataType]: features['latitude'] + ',' + features['longitude']
    //             };
    //             switch (dataType) {
    //                 case 'startCoor':
    //                     value['road_Name'] = features['roadName'];
    //                     break;
    //                 case 'QendCoor':
    //                     value['q_End_Link_ID'] = features['linkID'];
    //                     break;
    //             }
    //             // this.validateForm.patchValue(value);
    //         }
    //     });
    // }
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        // this.getData();
        const { queryStartTime, queryEndTime, startTimeRange, endTimeRange } = this.getTimeFormat();
        const a = `startDateRange=${queryStartTime},endDateRange=${queryEndTime},weekday=${this.includeSelect}`;
        const b = `startTimeRange=${startTimeRange},endTimeRange=${endTimeRange},interval=${this.intervalSelect},deviceId=${
            this.detectorID
        }`;
        const queryData = `${a},${b}`;
        this.getTableData(queryData);
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        // this.getData();
        const { queryStartTime, queryEndTime, startTimeRange, endTimeRange } = this.getTimeFormat();
        const a = `startDateRange=${queryStartTime},endDateRange=${queryEndTime},weekday=${this.includeSelect}`;
        const b = `startTimeRange=${startTimeRange},endTimeRange=${endTimeRange},interval=${this.intervalSelect},deviceId=${
            this.detectorID
        }`;
        const queryData = `${a},${b}`;
        this.getTableData(queryData);
    }

    // time range点击确定
    onOk(result: Date): void {}

    getTimeStamp() {
        const nowdate = new Date();
        nowdate.setMonth(nowdate.getMonth() - 3);
        const y = nowdate.getFullYear();
        const m = nowdate.getMonth() + 1;
        const d = nowdate.getDate();
        const formatwdate = y + '-' + m + '-' + d;
        return new Date(formatwdate).getTime();
    }

    onChange(event): void {
        this.hisDateRange = event;
    }

    getTimeFormat(): any {
        const t1 = moment(this.dateRange[0]).format('YYYY-MM-DD 00:00:00');
        const t2 = moment(this.dateRange[1]).format('YYYY-MM-DD 23:59:59');
        const queryStartTime = t1.split(' ')[0];
        const queryEndTime = t2.split(' ')[0];
        const startTimeRange = t1.split(' ')[1];
        const endTimeRange = t2.split(' ')[1];
        return { queryStartTime, queryEndTime, startTimeRange, endTimeRange };
    }

    // public includeSearch() { }
    // public intervalSearch() { }
    // public startTimeSearch() {
    //     const a = new Date(this.startTime).getTime();
    //     const startTimeRange = moment(a).format('HH:mm');
    //     this.startTimeRange = startTimeRange;
    // }
    // public endTimeSearch() {
    //     const a = new Date(this.endTime).getTime();
    //     const endTimeRange = moment(a).format('HH:mm');
    //     this.endTimeRange = endTimeRange;
    // }
    public sourceSearch() {
        // if (this.sourcelSelect === 'current') {
        //     this.flag = true;
        // } else {
        //     this.flag = false;
        // }
    }

    // 禁用今天之后的日期选择
    range(start: number, end: number): number[] {
        const result: number[] = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };

    disabledDateTime: object = () => {
        return {
            nzDisabledHours: () => this.range(0, 24).splice(4, 20),
            nzDisabledMinutes: () => this.range(30, 60),
            nzDisabledSeconds: () => [55, 56]
        };
    };

    disabledRangeTime: object = (value: Date[], type: 'start' | 'end') => {
        if (type === 'start') {
            return {
                nzDisabledHours: () => this.range(0, 60).splice(4, 20),
                nzDisabledMinutes: () => this.range(30, 60),
                nzDisabledSeconds: () => [55, 56]
            };
        }
        return {
            nzDisabledHours: () => this.range(0, 60).splice(20, 4),
            nzDisabledMinutes: () => this.range(0, 31),
            nzDisabledSeconds: () => [55, 56]
        };
    };
}
